package org.changchen.fgt.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;
import org.changchen.fgt.dto.AcgBgmOnAirDto;
import org.changchen.fgt.dto.AcgBgmSiteDto;
import org.changchen.fgt.dto.AcgWeekDto;
import org.changchen.fgt.service.AcgService;
import org.changchen.fgt.utils.BgmDateUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.hutool.core.collection.CollectionUtil;

@Service
public class AcgServiceImpl implements AcgService{
	
	
	private static final String URL_BGM_ONAIR = "https://bgmlist.com/api/v1/bangumi/onair";
	
	
	private static final String URL_BGM_SITE = "https://bgmlist.com/api/v1/bangumi/site";
	
	
	private static final String[] WEEK_DAYS = {"周一","周二","周三","周四","周五","周六","周日"};
	
	
	@Override
	public List<AcgWeekDto> acgList(){
		
		List<AcgBgmOnAirDto> onAirList = this.bgmList();
		Map<String,AcgBgmSiteDto> siteMap = this.bgmSite();
		
		if(CollectionUtil.isEmpty(onAirList)) {
			Collections.emptyList();
		}
		
		List<AcgWeekDto.AcgItemDto> infoList = new ArrayList<>();
		
		for(AcgBgmOnAirDto onAir : onAirList) {
			
			AcgWeekDto itemBuilder = new AcgWeekDto();
			AcgWeekDto.AcgItemDto itemDto = itemBuilder.new AcgItemDto();
			
			// Date beginTime = BgmDateUtil.parse(itemDto.getBeginDate());
			Date beginTime = onAir.getBegin();
			String week = BgmDateUtil.week(beginTime, true);
			String date = BgmDateUtil.beginDate(beginTime);
			String time = BgmDateUtil.time(beginTime);
			
			itemDto.setWeek(week);
			itemDto.setBeginDate(date);
			itemDto.setTime(time);
			String aTag = "<a href='/home?wd=%s'>%s</a>";
			itemDto.setNameJp(String.format(aTag, onAir.getTitle(), onAir.getTitle()));
			itemDto.setOfficalSite(onAir.getOfficialSite());
			itemDto.setIsNew(BgmDateUtil.isNew(beginTime));
			
			List<String> nameCnList = onAir.getTitleTranslate().getZhHans();
			if(CollectionUtil.isNotEmpty(nameCnList)) {
				for(int i = 0; i < nameCnList.size(); i++) {
					if(i == 0) {
						itemDto.setNameCn(nameCnList.get(0));
					}else {
						
						itemDto.setNameJp(itemDto.getNameJp()  + " / " + String.format(aTag, nameCnList.get(i), nameCnList.get(i)));
					}
				}
			} else {
				itemDto.setNameCn(onAir.getTitle());
			}
			
			// 
			List<AcgWeekDto.Site> sites = new ArrayList<>();
			for(AcgBgmOnAirDto.Site site : onAir.getSites()) {
				AcgBgmSiteDto bgmSite = siteMap.get(site.getSite());
				String id = site.getId();
				
				String name = bgmSite.getTitle();
				String url = bgmSite.getUrlTemplate().replace("{{id}}", id);
				
				if("bangumi".equals(site.getSite())) {
					itemDto.setBangumiSite(url);
					continue;
				}
				
				AcgWeekDto.Site resuleSite = itemBuilder.new Site(name, url);
				sites.add(resuleSite);
			}
			itemDto.setSites(sites);
			
			infoList.add(itemDto);
		}
		
		
		Map<String, List<AcgWeekDto.AcgItemDto>> infoMap= infoList.stream()
				.collect(Collectors.groupingBy(AcgWeekDto.AcgItemDto::getWeek));
		
		List<AcgWeekDto> resultList = new ArrayList<>();
		for(String week : WEEK_DAYS) {
			AcgWeekDto weekDto = new AcgWeekDto();
			weekDto.setWeek(week);
			// 按播放时间排序
			List<AcgWeekDto.AcgItemDto> itemList = infoMap.get(week);
			Collections.sort(itemList);
			weekDto.setList(itemList);
			String todayWeek = BgmDateUtil.week(new Date(), true);
			weekDto.setIsToday(todayWeek.equals(week));
			resultList.add(weekDto);
		}
		
		
		return resultList;
	}
	
	
	
	@Override
	public List<AcgBgmOnAirDto> bgmList() {
		
		String onairList = WebClient.create().get().uri(URL_BGM_ONAIR).retrieve().bodyToMono(String.class).block();
        if(StringUtils.isBlank(onairList)) {
        	return Collections.emptyList();
        }
		
        JSONObject json = JSONObject.parseObject(onairList);
        return JSONArray.parseArray(json.getString("items"), AcgBgmOnAirDto.class);
	}
	
	@Override
	public Map<String,AcgBgmSiteDto> bgmSite(){
		
		String siteList = WebClient.create().get().uri(URL_BGM_SITE).retrieve().bodyToMono(String.class).block();
        if(StringUtils.isBlank(siteList)) {
        	return new HashMap<>();
        }
        
        Map<String,AcgBgmSiteDto> resultMap = new HashMap<>();
        JSONObject tempMap = JSONObject.parseObject(siteList);
        for(String key : tempMap.keySet()) {
        	resultMap.put(key, JSONObject.parseObject(tempMap.getString(key), AcgBgmSiteDto.class));
        }
		
        return resultMap;
        
	}
	

}
